package contestseeker.action;

import java.util.*;
import java.io.*;

import contestseeker.visitors.*;


public class ConfigReader {
	private static Map<String, VisitorBase> vmap;
	private static String default_config = 
		"NanKai,ZJU,UVA,PKU1,HDU1,PKU2,BUPT,BNU,WHU,HUST,TJU1,HDU2,TJU2,BJTU,FZU,HIT,HNU,HRBEU,JLU,NIT,NUAA,SGU,SPOJ";
	static {
		vmap = new HashMap<String, VisitorBase>();
		vmap.put("BJTU", new BJTU());	
		vmap.put("BNU", new BNU());
		vmap.put("BUPT", new BUPT());
		vmap.put("FZU", new FZU());
		vmap.put("HDU1", new HDU1());
		vmap.put("HDU2", new HDU2());
		vmap.put("HIT", new HIT());
		vmap.put("HNU", new HNU());
		vmap.put("HRBEU", new HRBEU());
		vmap.put("HUST", new HUST());
		vmap.put("JLU", new JLU());
		vmap.put("NIT", new NIT());
		vmap.put("NUAA", new NUAA());
		vmap.put("PKU1", new PKU1());
		vmap.put("PKU2", new PKU2()); 
		vmap.put("SGU", new SGU());
		vmap.put("SPOJ", new SPOJ());
		vmap.put("TJU1", new TJU1());
		vmap.put("TJU2", new TJU2());
		vmap.put("UVA", new UVA());
		vmap.put("WHU", new WHU());
		vmap.put("ZJU", new ZJU());
		vmap.put("NanKai", new NanKaiSeeker());
	}
	
	public static VisitorBase[] getVisitorsFromFile()
	{
		File f = new File("config.ini");
		FileReader fr = null;
		BufferedReader br = null;
		StringBuffer sbuf = new StringBuffer();
		boolean first = true;
		
		try {
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			
			String line, key;
			while ((line = br.readLine()) != null)
			{
				if (line.isEmpty() || line.charAt(0) == '#')
					continue;
				key = line.trim();
				if (vmap.containsKey(key))
				{
					if (first) {
						sbuf.append(key);
						first = false;
					} else {
						sbuf.append("," + key);
					}
				}
			}
			
			br.close();
			fr.close();
			return getVisitorsFromString(sbuf.toString());
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return vmap.values().toArray(new VisitorBase[vmap.size()]);
	}
	
	public static VisitorBase[] getVisitorsFromString(String vlist)
	{
		ArrayList<VisitorBase> array = new ArrayList<VisitorBase>();
		String ss[] = vlist.split(",");
		
		for (int i = 0; i < ss.length; ++i)
			if (vmap.containsKey(ss[i]))
				array.add(vmap.get(ss[i]));
		return array.toArray(new VisitorBase[array.size()]);
	}
	
	public static VisitorBase[] getAllVisitors()
	{
		return getVisitorsFromString(default_config);
	}
	
}
